package com.xsmart.fileserver.web;

import com.xsmart.fileserver.entity.FileMeta;
import com.xsmart.fileserver.services.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.LinkedList;


@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping("/controller")
public class FileController {
    @Autowired
    private FileUploadService fileUploadService;

    /***************************************************
     * URL: /rest/controller/upload
     * upload(): receives files
     * @param request : MultipartHttpServletRequest auto passed
     * @param response : HttpServletResponse auto passed
     * @return LinkedList<FileMeta> as json format
     ****************************************************/
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody
    LinkedList<FileMeta> upload(MultipartHttpServletRequest request, HttpServletResponse response) {
        return fileUploadService.adminuUpload(request, response);
    }
    @RequestMapping(value = "/user_upload", method = RequestMethod.POST)
    public @ResponseBody
    LinkedList<FileMeta> userUpload(MultipartHttpServletRequest request, HttpServletResponse response) {
        return fileUploadService.userUpload(request, response);
    }
    /***************************************************
     * URL: /rest/controller/get/{value}
     * get(): get file as an attachment
     * @param response : passed by the server
     * @param value : value from the URL
     * @return void
     ****************************************************/
    @RequestMapping(value = "/get/{value}", method = RequestMethod.GET)
    public void get(HttpServletResponse response, @PathVariable String value) {
//        FileMeta getFile = files.get(Integer.parseInt(value));
//        try {
//            response.setContentType(getFile.getFileType());
//            response.setHeader("Content-disposition", "attachment; filename=\"" + getFile.getFileName() + "\"");
//            FileCopyUtils.copy(getFile.getBytes(), response.getOutputStream());
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
    }
}
